package ejb;

import java.util.List;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dto.CandidateDTO;
import entitymanagers.CandidateManager;
import utils.AbstractBean;
import model.Candidate;
import model.Party;

@Stateless
@LocalBean
public class CandidateManagerBean extends AbstractBean<Candidate> implements CandidateManager{
	
	@PersistenceContext
	private EntityManager em;
	@Resource
	private SessionContext context;
	
	public CandidateManagerBean() {
		super(Candidate.class);
	}

	@Override
	public CandidateDTO getCandidateByID(String ID) {
		try{
			return convertToDTO(find(ID));
		}
		catch (Exception e){
			return new CandidateDTO();
		}
	}

	@Override
	public CandidateDTO getCandidateByID() {
		return convertToDTO(find(context.getCallerPrincipal().getName()));
	}

	@Override
	public CandidateDTO[] getCandidates() {
		try{
			return convertToDTO(findAll());
		}
		catch (Exception e){
			return new CandidateDTO[0];
		}
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}
	public CandidateDTO convertToDTO(Candidate candidate){
		CandidateDTO candidateDTO = new CandidateDTO();
		candidateDTO.setCitizen(candidateDTO.getCitizen());;
		candidateDTO.setCv(candidateDTO.getCv());
		candidateDTO.setDateCandidacy(candidateDTO.getDateCandidacy());
		candidateDTO.setMotLetter(candidateDTO.getMotLetter());
		return candidateDTO;
	}
	private CandidateDTO[] convertToDTO(List<Candidate> findAll) {
		if(findAll != null){
			CandidateDTO[] candidates = new CandidateDTO[findAll.size()];
			int i = 0;
			for(Candidate c: findAll){
				candidates[i] = convertToDTO(c);
				i++;
			}
			return candidates;
		}
		return null;
	}
	
	
}
